package socket.homework2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author lhn
 * @date 2024-04-26 21:46
 * 接收端
 */

public class Homework02ReceiverA {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(8888);
        System.out.println("接收端已启动...");
        byte[] buffer = new byte[64 * 1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
        datagramSocket.receive(datagramPacket);
        int length = datagramPacket.getLength();
        byte[] data = new byte[64 * 1024];
        data = datagramPacket.getData();
        String s = new String(data, 0, length);
        System.out.println("s" + s);
        String answer = "";
        switch (s) {
            case "四大名著是哪些":
                answer = "四大名著《水浒传》《三国演义》《西游记》《红楼梦》";
                break;
            default:
                answer = "what?";
                break;
        }
        System.out.println("answer is" + answer);
        data = answer.getBytes();
        datagramPacket = new DatagramPacket(
                data, data.length, InetAddress.getByName("192.168.72.1"), 8889
        );
        System.out.println("回复消息成功");
        datagramSocket.send(datagramPacket);
        System.out.println("A端退出...");
    }
}
